class Solution {
public:
    int search(vector<int>& nums, int target) {
        int k = 0, n = nums.size();
        if(n==0) return -1;
        for (; k < n - 1; k++) {
            if (nums[k] > nums[k + 1])
                break;
        }
        // 在旋转数组中执行二分查找
        int l = 0, r = n - 1;
        while (l <= r) { // 注意这里应该是 l <= r
            int mid = l + (r - l) / 2;
            int realMid = (mid + k + 1) % n; // 将 mid 转换回实际数组中的位置

            if (nums[realMid] == target) return realMid;
            else if (nums[realMid] < target) l = mid + 1;
            else r = mid - 1;
        }
        
        return -1; // 如果没有找到目标值
    }
    
};


//O(log n)时间复杂度的解法：
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int n=nums.size();
        if(n==0) return -1;

        int l=0,r=n-1;
        while(l<=r)
        {
            int mid=l+(r-l)/2;
            if(nums[mid]==target) return mid;

            if(nums[mid]>=nums[l])
            {
                if(nums[l]<=target&&target<nums[mid]) r=mid-1;
                else l=mid+1;
            }
            else{
                if(nums[mid]<target&&target<=nums[r]) l=mid+1;
                else r=mid-1;
            }
        }
        return -1;
    }
};